package com.nzw.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by 许湛司 on 2017/4/28.
 */
public class FileUtils {
    /**
     * 把文件转成字节数组
     * @param filename
     * @return
     */
    public static byte[] file2ByteArray(String filename) {
        File f = new File(filename);
        if (!f.exists()) {
            try {
                throw new FileNotFoundException(filename);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
            }
            return byteBuffer.array();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
